ext.define('extension.requestview', function() {

var messages = extension.messages;
var utils = extension.utils;
var slider = extension.slider;
var requests = {};
var dirty = false;

function requestinfo(elm) {
    return function(n, v, x) {
        var l = $x('prop');
        l.querySelector('.prop-info-name').textContent = n;
        l.querySelector('.prop-info-value').textContent = v;
        l.querySelector('.prop-info-value').className += (x || '');
        elm.appendChild(l);
    };
}

function onReferrer(e) {
    if (e.relayTarget.classList.contains('selected'))
        return;

    updateRequestList(e.relayTarget.textContent);

    e.currentTarget.querySelector('.selected').classList.remove('selected');
    e.relayTarget.classList.add('selected');

    utils.overlay('', '#resources .view:last-child');
}

function onRequest(e) {
    var origin = $('referrer').querySelector('.selected').textContent;
    var m = requests[origin][getChildPosition(e.relayTarget)];
    var j = $x('info');
    var info = requestinfo(j.querySelector('ol'));
    info('URL:', m['src']);
    info('Status:', utils.stringMap(m['status']), ' status-icon status-' + m['status']);
    info('Host:', utils.origin(m['src']));
    info('Referer:', m['ref']);
    info('Width:', m['width']);
    info('Height:', m['height']);
    info('Type:', m['type']);
    info('ScriptAccess:', m['access']);
    info('Flash Vars:', m['vars']);
    $('resources').querySelector('.view:last-child').appendChild(j);
}

function onClear(e) {
    utils.overlay('', '#resources .view:last-child');
}

function onStatusbar(e) {
    if (e.relayTarget.classList.contains('statusbar-reload'))
        messages.send('requests-reload');
}

function onSlide(e) {
    e.preventDefault();
    utils.glass('x', slider.create(e));
}

function updateRefererList(o) {
    var l = document.createElement('li');
    l.className = 'list-item';
    l.textContent = o;
    if (getChildPosition($('referrer').appendChild(l)) === 0)
        l.classList.add('selected');
}

function updateRequestList(o) {
    var r = $('request');
    r.textContent = '';
    var t, u, v = requests[o];
    for (var i = 0; i < v.length; i++) {
        t = $x('request');
        l = t.querySelector('.list-item');
        l.classList.add('status-icon');
        l.classList.add('status-' + v[i]['status']);
        l.textContent = v[i]['src'] || '\u00A0';
        r.appendChild(t);
    }
    r.lastElementChild.scrollIntoView();
}

function changeSummary(count) {
    var icon = str = '';
    if (!count) str = utils.strings.NOREQ, icon = 'warning-icon-small';
    else str = utils.format(utils.strings.REQCNT, count, count > 1 ? 's' : '');
    utils.summary(icon, str, '#resources .statusbar-summary');
}

function updateViews(data) {
    if (data.info.length === 0)
        return;

    var info = data.info.map(function(i) {
        i.ref = data.url;
        return i;
    });

    var origin = utils.origin(data.url) || ':blank';
    var found = origin in requests;
    var item = requests[origin] || [];
    var ids = [];
    for (var i = 0; i < item.length; i++)
        ids.push(item[i].id);
    for (var i = 0; i < info.length; i++) {
        var index = ids.indexOf(info[i].id);
        if (index == -1)
            item.push(info[i]);
        else
            item[index] = info[i];
    }
    requests[origin] = item;

    if (!found)
        updateRefererList(origin);
    if ($('referrer').querySelector('.selected').textContent === origin)
        updateRequestList(origin);

    var count = 0;
    for (var k in requests)
        count += Object.keys(requests[k]).length;
    changeSummary(count);

    dirty = true;
}

function resetViews() {
    requests = {};
    dirty = false;
    $('referrer').textContent = '';
    $('request').textContent = '';
    utils.overlay('', '#resources .view:last-child');
    changeSummary('');
}

return {
    bind: function() {
        relayEvent($('referrer'), 'mousedown', '.list-item', onReferrer);
        relayEvent($('request'), 'click', '.list-item', onRequest);
        relayEvent($('resources').querySelector('.view:last-child'), 'click', '.delete', onClear);
        relayEvent($('resources').querySelector('.status-bar'), 'click', '.statusbar-item', onStatusbar);
        $('resources').querySelector('.splitter').addEventListener('mousedown', onSlide);
    },
    reset: resetViews,
    update: updateViews
};

});
